<?php
/**
 * Created by PhpStorm.
 * User: idcu
 * Date: 2016/3/2
 * Time: 9:19
 */
namespace Assistant\Model;
use IDCU\Model\RelationModel;

class FamilyMemberModel extends RelationModel
{
    protected $_validate = array(
        array('customer_id','require','客户ID必填'),
        array('family_id','require','房间ID必填'),
        array('customer_id,family_id','','客户ID、房间ID共同决定唯一性',1,'unique',1),
        array('customer_id,family_id','check2','客户ID、房间ID共同决定唯一性',1,'callback',2)
    );

    protected $_link = array(
        'Customer' => array(
            'mapping_type'  => self::BELONGS_TO,
            'class_name'    => 'Customer',
            'foreign_key'   => 'customer_id',
            'mapping_name'  => 'customer'
        ),
        'Family' => array(
            'mapping_type'  => self::BELONGS_TO,
            'class_name'    => 'Family',
            'foreign_key'   => 'family_id',
            'mapping_name'  => 'family'
        ),
    );

    public function _before_insert(&$data, $options)
    {
        parent::_after_insert($data, $options); // TODO: Change the autogenerated stub
        $data['name'] = M('Customer')->where(array('id'=>$data['customer_id']))->find()['name'];
    }

    public function _after_insert($data, $options)
    {
        parent::_after_insert($data, $options); // TODO: Change the autogenerated stub
        $customers = $this->where(array('family_id'=>$data['family_id']))->order(array('create_time'))->select();
        $i = 0;
        foreach($customers as $k=>$v){
            if($v['prefix'] == ''){
                $this->save(array('id'=>$v['id'],'prefix'=>'成员'));
                $i++;
            }elseif($v['prefix'] == '成员'){
                $i++;
            }
        }
        if($i == count($customers)){
            $this->save(array('id'=>$customers[0]['id'],'prefix'=>'户主'));
        }
    }

    function check2($param){
        $where['customer_id'] = $param['customer_id'];
        $where['family_id'] = $param['family_id'];
        $count = $this->where($where)->count();
        if($count > 1){
            return false;
        }else{
            return true;
        }
    }
}